<link rel="import" href="../../bower_components/polymer/polymer-element.html">

<link rel="import" href="../../bower_components/vaadin-ordered-layout/vaadin-vertical-layout.html">
<link rel="import" href="../../bower_components/vaadin-ordered-layout/vaadin-horizontal-layout.html">
<link rel="import" href="../../bower_components/vaadin-text-field/vaadin-text-field.html">
<link rel="import" href="../../bower_components/vaadin-select/vaadin-select.html">
<link rel="import" href="../../bower_components/vaadin-date-picker/vaadin-date-picker.html">
<link rel="import" href="../../bower_components/vaadin-rich-text-editor/vaadin-rich-text-editor.html">
<link rel="import" href="../../bower_components/vaadin-button/vaadin-button.html">
<link rel="import" href="../../bower_components/vaadin-tabs/vaadin-tabs.html">

<link rel="import" href="../../bower_components/vaadin-notification/vaadin-notification.html">

<link rel="import" href="../../bower_components/vaadin-form-layout/vaadin-form-layout.html">
<link rel="import" href="../../bower_components/vaadin-form-layout/vaadin-form-item.html">

<link rel="import" href="../../bower_components/vaadin-board/vaadin-board.html">
<link rel="import" href="../../bower_components/vaadin-board/vaadin-board-row.html">

<link rel="import" href="../../bower_components/vaadin-grid-pro/vaadin-grid-pro-edit-column.html">
<link rel="import" href="../../bower_components/vaadin-grid/vaadin-grid-sorter.html">
<link rel="import" href="../../bower_components/vaadin-grid/vaadin-grid-column-group.html">
<link rel="import" href="../../bower_components/vaadin-grid-pro/vaadin-grid-pro.html">

<link rel="import" href="../../bower_components/iron-icon/iron-icon.html">

<link rel="import" href="../../bower_components/vaadin-lumo-styles/color.html">
<link rel="import" href="../../bower_components/vaadin-lumo-styles/typography.html">
<link rel="import" href="../../bower_components/vaadin-lumo-styles/sizing.html">
<link rel="import" href="../../bower_components/vaadin-lumo-styles/font-icons.html">
<link rel="import" href="../../bower_components/vaadin-lumo-styles/badge.html">

<link rel="import" href="./link-banner.html">

<link rel="import" href="invoice-editor-styles.html">

<script src="../data/dummy-data.js"></script>

<dom-module id="invoice-editor-app">
  <template>
    <style include="invoice-editor-app-styles"></style>
    <style include="lumo-badge"></style>
    <div id="container">
      <link-banner source-link="https://github.com/vaadin/ui-examples/tree/master/data-entry/invoice-editor"></link-banner>
      <div class="controls-line">
        <vaadin-horizontal-layout class="invoice-details" theme="padding">
          <span>Invoice #3225</span>
          <small>Draft saved 5 minutes ago</small>
        </vaadin-horizontal-layout>
        <vaadin-horizontal-layout class="controls-line-buttons">
          <vaadin-button on-click='__discardChanges' theme="error tertiary">Discard changes</vaadin-button>
          <vaadin-button on-click='__saveDraft' theme="tertiary">Save draft</vaadin-button>
          <vaadin-button on-click='__sendInvoice' theme="primary">Send</vaadin-button>
        </vaadin-horizontal-layout>
      </div>
      <vaadin-board>
        <vaadin-board-row>
          <div>
            <vaadin-form-layout responsive-steps="[[inputLayoutSteps]]">
              <vaadin-text-field class="large" colspan="2" label="Invoice Name" value="Trip to Italy"></vaadin-text-field>
              <vaadin-select label="Employee" value="Manolo">
                <template>
                  <vaadin-list-box>
                    <vaadin-item>Manolo</vaadin-item>
                    <vaadin-item>Joonas</vaadin-item>
                    <vaadin-item>Matti</vaadin-item>
                  </vaadin-list-box>
                </template>
              </vaadin-select>
              <vaadin-date-picker label="Date" value="2018-12-12"></vaadin-date-picker>
            </vaadin-form-layout>
          </div>
          <div board-cols="2">
            <vaadin-rich-text-editor theme="compact" value="{{rteValue}}"></vaadin-rich-text-editor>
          </div>
        </vaadin-board-row>
      </vaadin-board>
      <div class="controls-line">
        <vaadin-button theme="tertiary" id="add-line" on-click="__addLine">
          <span>Add credit card transaction</span>
        </vaadin-button>
      </div>
      <vaadin-grid-pro multi-sort theme="column-borders compact" items="[[items]]" on-item-property-changed="onItemPropertyChanged">
        <vaadin-grid-column-group resizable>
          <vaadin-grid-pro-edit-column path="product" header="Product" header-renderer="[[sorterRenderer]]"></vaadin-grid-pro-edit-column>
          <vaadin-grid-pro-edit-column width="300px" path="description" header="Description" header-renderer="[[sorterRenderer]]"></vaadin-grid-pro-edit-column>
          <vaadin-grid-pro-edit-column text-align="end" path="price" header="Price" header-renderer="[[sorterRenderer]]"></vaadin-grid-pro-edit-column>
          <vaadin-grid-pro-edit-column path="currency" header="Currency" editor-type="select" header-renderer="[[sorterRenderer]]" renderer="[[currencyRenderer]]" editor-options="[[currencyOptions]]"></vaadin-grid-pro-edit-column>
          <vaadin-grid-pro-edit-column text-align="end" path="vat" header="VAT" header-renderer="[[sorterRenderer]]" renderer="[[vatRenderer]]"></vaadin-grid-pro-edit-column>
          <vaadin-grid-pro-edit-column text-align="end" path="amount" header="Amount" header-renderer="[[sorterRenderer]]"></vaadin-grid-pro-edit-column>
          <vaadin-grid-pro-edit-column path="category" header="Category" editor-type="select" header-renderer="[[sorterRenderer]]" editor-options="[[categoryOptions]]"></vaadin-grid-pro-edit-column>
          <vaadin-grid-pro-edit-column path="order" header="Status" editor-type="checkbox" header-renderer="[[sorterRenderer]]" renderer="[[orderRenderer]]"></vaadin-grid-pro-edit-column>
          <vaadin-grid-pro-edit-column text-align="end" path="total" header="Total" header-renderer="[[sorterRenderer]]" renderer="[[totalRenderer]]"></vaadin-grid-pro-edit-column>
          <vaadin-grid-column width="70px" text-align="center" renderer="[[deleteRenderer]]"></vaadin-grid-edit-column>
        </vaadin-grid-column-group>
      </vaadin-grid-pro>
      <div class="controls-line footer">
        <span>Total in</span>
        <vaadin-select class="currency-selector" theme="custom" value="EUR">
          <template>
            <vaadin-list-box>
              <vaadin-item>USD</vaadin-item>
              <vaadin-item>EUR</vaadin-item>
              <vaadin-item>GBP</vaadin-item>
            </vaadin-list-box>
          </template>
        </vaadin-select>
        <span class="total">812</span>
      </div>
    </div>
  </template>

  <script>
    /**
     * @customElement
     * @polymer
     */
    class InvoiceEditorApp extends Polymer.Element {
      static get is() { return 'invoice-editor-app'; }
      static get properties() {
        return {
          prop1: {
            type: String,
            value: 'invoice-editor-app'
          },

          items: {
            type: Array,
            value: () => window.Vaadin.dummyData
          },

          inputLayoutSteps: {
            type: Array,
            value: () => [
              {minWidth: 0, columns: 1, labelsPosition: 'top'},
              {minWidth: '30em', columns: 2}
            ]
          },

          currencyOptions: {
            type: Array,
            value: () => ['EUR', 'USD', 'GBP']
          },

          categoryOptions: {
            type: Array,
            value: () => ['Team expenses', 'Personal']
          },

          rteValue: {
            type: String,
            value: `[
              {"attributes":{"bold":true},"insert":"Team lunch participants:"},
              {"insert":" Manolo, Joonas, and Matti\\nTraveling in Antwerp:\\nMetro from the hotel to the venue"},
              {"attributes":{"list":"bullet"},"insert":"\\n"},
              {"insert":"Taxi from the airport to the hotel"},
              {"attributes":{"list":"bullet"},"insert":"\\n"}
            ]`
          }
        };
      }

      sorterRenderer(root, column) {
        root.innerHTML = `<vaadin-grid-sorter path="${column.path}">${column.header}</vaadin-grid-sorter>`;
      }

      currencyRenderer(root, column, rowData) {
        let signContainer = root.firstElementChild;
        if (!signContainer) {
          signContainer = document.createElement('div');
        }

        signContainer.innerText = rowData.item.currency;
        signContainer.className = 'icon-' + rowData.item.currency.toLowerCase();
        root.appendChild(signContainer);
      }

      vatRenderer(root, column, rowData) {
        root.textContent = rowData.item.vat + '%';
      }

      orderRenderer(root, column, rowData) {
        root.innerHTML = rowData.item.order ? '<span theme="badge success">Completed</span>' : '<span theme="badge">Open</span>';
      }

      totalRenderer(root, column, rowData) {
        let sign = '';
        const currencyName = rowData.item.currency;

        if (currencyName === 'EUR') {
          sign = '€';
        } else if (currencyName === 'USD') {
          sign = '$';
        } else if (currencyName  === 'GBP') {
          sign = '£';
        }

        root.textContent = rowData.item.total ? sign + rowData.item.total : '';
      }

      deleteRenderer(root, column, rowData) {
        if (!root.firstElementChild) {
          const deleteBtn = document.createElement('vaadin-button');
          deleteBtn.classList.add('delete-button');
          deleteBtn.innerHTML = '<iron-icon icon="lumo:cross" slot="prefix"></iron-icon>';
          deleteBtn.setAttribute('theme', 'small icon');
          deleteBtn.addEventListener('click', e => {
            this.items = this.items.filter(i => i !== deleteBtn._rowItem);
          });
          root.appendChild(deleteBtn);
        }
        root.firstElementChild._rowItem = rowData.item;
      }

      onItemPropertyChanged(e) {
        const msg = e.detail.path.charAt(0).toUpperCase() + e.detail.path.slice(1) +
                      ' was updated to be: ' + e.detail.value +
                      ' for product ' + e.detail.item.product;

        this.__appendInfoNotification(msg);
      }

      ready() {
        super.ready();
        // deleteRenderer refers to this so it needs to be bound
        this.deleteRenderer = this.deleteRenderer.bind(this);
      }

      __discardChanges() {
        this.__appendInfoNotification('Changes were discarded!');
      }

      __saveDraft() {
        this.__appendInfoNotification('Changes were saved!');
      }

      __sendInvoice() {
        this.__appendInfoNotification('Invoice was sent!');
      }

      __appendInfoNotification(msg) {
        const notify = window.document.createElement('vaadin-notification');
        notify.renderer = root => root.textContent = msg;

        window.document.body.appendChild(notify);
        notify.position = 'bottom-start';
        notify.duration = 3000;
        notify.opened = true;
        notify.addEventListener('opened-changed', () => {
          window.document.body.removeChild(notify);
        });
      }

      __addLine() {
        this.unshift('items', {
          "product": "",
          "description": "",
          "price": 0,
          "currency": "",
          "vat": 0,
          "order": false,
          "amount": 0,
          "category": "",
          "total": 0
        });
      }
    }

    window.customElements.define(InvoiceEditorApp.is, InvoiceEditorApp);

    /**
     * @namespace InvoiceEditorApp
     */
    window.InvoiceEditorApp = window.InvoiceEditorApp || {};
  </script>
</dom-module>
